import { defineStore } from "pinia";
import { AuthState } from "@/stores/interface";
import { getFlatMenuList, getShowMenuList, getAllBreadcrumbList } from "@/utils";
import { getRouters, getPermBtm } from "@/api/modules/login";
import { useUserStore } from "@/stores/module/userInfo";

// 定义 API 响应类型
interface ApiResponse<T = any> {
  Code: number;
  Msg?: string;
  Data: T;
}

// 菜单标准化处理函数
const normalizeMenu = (menu: Menu.MenuOptions): Menu.MenuOptions => {
  // 确保 children 存在且是数组
  const children = menu.children || [];
  
  return {
    ...menu,
    meta: {
      ...menu.meta,
      isHide: menu.meta.isHide ?? false,
      isFull: menu.meta.isFull ?? false,
      isAffix: menu.meta.isAffix ?? false,
      isKeepAlive: menu.meta.isKeepAlive ?? false,
    },
    children: children.map(normalizeMenu)
  };
};

export const useAuthStore = defineStore({
  id: "auth",
  
  state: (): AuthState => ({
    authButtonList: [],
    authMenuList: []
  }),
  
  getters: {
    authButtonListGet: state => state.authButtonList,
    authMenuListGet: state => state.authMenuList,
    showMenuListGet: state => getShowMenuList(state.authMenuList),
    flatMenuListGet: state => getFlatMenuList(state.authMenuList),
    breadcrumbListGet: state => getAllBreadcrumbList(state.authMenuList),
  },
  
  actions: {
    /**
     * 获取用户按钮权限列表
     */
    async getAuthButtonList() {
      try {
        const res = await getPermBtm() as ApiResponse<{ perms: string }[]>;
        
        if (res.Code === 200) {
          this.authButtonList = res.Data
            .map(item => item.perms)
            .filter(perm => !!perm) as string[];
        }
      } catch (error) {
        this.authButtonList = [];
        console.error("获取按钮权限失败:", error);
        throw error;
      }
    },

    /**
     * 获取用户菜单权限列表（从后端API获取）
     */
    async getAuthMenuList() {
      try {
        // 调用后端API获取菜单数据（添加类型断言）
        const res = await getRouters() as ApiResponse<Menu.MenuOptions[]>;
        
        // 检查响应是否有效
        if (res.Code !== 200 || !res.Data) {
          throw new Error("无效的菜单数据响应");
        }
        
        // 使用标准化函数处理菜单数据
        const normalizedData = res.Data.map(normalizeMenu);
        this.authMenuList = normalizedData;
        
      } catch (error) {
        this.authMenuList = [];
        console.error("获取菜单权限失败:", error);
        throw error;
      }
    }
  }
});